package hotel.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hotel.entity.Category;
import hotel.entity.Price;
import hotel.service.ICategoryService;
import hotel.service.IPriceService;
import util.JSONUtil;

@Controller
public class PriceController {
	// Jackson
	private final static ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private ICategoryService<Category> categoryService;
	@Autowired
	IPriceService<Price> priceService;

	@RequestMapping(value = "priceManagement")
	public String priceManagement() {
		return "price/pricelist";
	}

	@ResponseBody
	@RequestMapping(value = "pricelist")
	public String getPriceList() {
		String json = null;
		try {
			mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
			json = mapper.writeValueAsString(priceService.listAll("Price"));
			json = "{\"data\":" + json + "}";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "addPrice", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "price/add";
	}

	@ResponseBody
	@RequestMapping(value = "addPrice", method = RequestMethod.POST)
	public String addPrice(Price price) {
		if (priceService.save(price))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}

	@RequestMapping(value = "editPrice", method = RequestMethod.GET)
	public String edit(int priceid, Model model) {
		model.addAttribute("price", priceService.findById(Price.class, priceid));
		return "price/edit";
	}

	@ResponseBody
	@RequestMapping(value = "editPrice", method = RequestMethod.POST)
	public String editPrice(Price price) {
		if (priceService.update(price))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}

	@ResponseBody
	@RequestMapping(value = "deletePrice")
	public String deletePrice(int priceid) {
		if (priceService.deleteById("Price", priceid))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
	
	/**
	 * 登记入住时获取应付总价
	 * @param categoryid房间类型
	 * @param amount房间数量
	 */
	@ResponseBody
	@RequestMapping(value="getPrice")
	public String getPrice(int categoryid,int amount) {
		double price=priceService.getPrice(categoryid);
		if(price>0)
			return "{\"price\":\""+price+"\",\"totalPrice\":\""+price*amount+"\"}";
		else
			return "{\"price\":\"错误！请到价格管理页面核对日期或价格\",\"totalPrice\":\"错误！请到价格管理页面核对日期或价格\"}";
	}
}
